<template>
  <div class="InspectionReview">
    <van-nav-bar
      left-arrow
      :border="false"
      @click-left="clickLeft"
      class="nav-bar">
      <template #title>
        <van-dropdown-menu>
          <van-dropdown-item
            v-model="navValue"
            :options="option1"
            @change="changeNav" />
        </van-dropdown-menu>
      </template>
      <template #right>
        <van-icon
          name="success"
          style="margin-right: 0.42667rem"
          @click="pass()"
          >通过</van-icon
        >
        <van-icon name="share-o" @click="reject()">驳回</van-icon>
      </template>
    </van-nav-bar>

    <div class="content">
      <van-row type="flex" align="center" style="border-bottom: 1px solid #eee">
        <van-col span="8">
          <van-field
            readonly
            clickable
            label=" 检验样品："
            v-model="sampleName"
            placeholder="请选择"
            input-align="center"
            @click="showSamplePicker = true" />
        </van-col>
        <van-col span="8">
          <van-field
            readonly
            clickable
            label=" 类型："
            v-model="logType"
            placeholder="请选择"
            input-align="center"
            @click="handleLogTypeClick" />
        </van-col>
        <van-col span="8" v-show="showPdfSelect">
          <van-field
            readonly
            clickable
            label=" pdf："
            v-model="pdfSelectValue.text"
            placeholder="请选择pdf"
            input-align="center"
            @click="showPdfTypePicker = true" />
        </van-col>
        <!-- <van-col
          span="6"
          style="display: flex; justify-content: flex-end; align-items: center">
          <van-button
            type="primary"
            icon="success"
            size="small"
            style="margin-right: 0.42667rem"
            @click="pass()"
            >通过</van-button
          >
          <van-button
            type="warning"
            icon="share-o"
            size="small"
            style="margin-right: 0.42667rem"
            @click="reject()"
            >驳回</van-button
          >
        </van-col> -->
      </van-row>
      <!-- <div id="reportPdf" ref="reportPdf"></div> -->
      <!-- <HPDFViewer :path="pdfUrl"></HPDFViewer> -->
			<div v-autoHeight style="text-align: center;">
			<HPDFViewer v-if="showPdf" :path="pdfUrl"></HPDFViewer>
			<img v-else class="pdf-img" :src="pdfUrl" />
			</div>

    </div>

    <van-popup
      v-if="showSamplePicker"
      v-model="showSamplePicker"
      position="bottom"
      round
      :style="{ height: '50%' }"
      :lock-scroll="false">
      <van-cascader
        v-model="sampleValue"
        :options="sampleArr"
        @close="showSamplePicker = false"
        @finish="onSampleFinish"
        :field-names="sampleNames" />
    </van-popup>
    <van-popup
      v-model="showTypePicker"
      position="bottom"
      round
      :style="{ height: '50%' }"
      :lock-scroll="false">
      <van-picker
        title="类型"
        show-toolbar
        :columns="columns"
        @confirm="onConfirm" />
    </van-popup>
    <van-popup
      v-model="showPdfTypePicker"
      position="bottom"
      round
      :style="{ height: '50%' }"
      :lock-scroll="false">
      <van-picker
        title="选择pdf"
        show-toolbar
        :columns="pdfColumns"
        @confirm="onPdfConfirm" />
    </van-popup>
    <van-popup
      v-model="showTextarea"
      get-container="body"
      position="center"
      style="width: 50vw; height: 40vh"
      class="rejectPopup">
      <div class="popup-content">
        <div style="font-size: 24px; margin: 15px 0 0 15px">驳回理由</div>
        <div
          class="popup-content__content"
          style="font-size: 16px; padding: 0 15px; box-sizing: border-box">
          <textarea rows="4" v-model="message"></textarea>
        </div>
        <div
          class="popup-content__footer"
          style="display: flex; justify-content: center">
          <van-button
            native-type="button"
            type="default"
            block
            style="margin-right: 0.2rem"
            @click="showTextarea = false"
            >取消</van-button
          >
          <van-button
            native-type="button"
            type="info"
            block
            @click="recallInfo()"
            >确定</van-button
          >
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script type="text/ecmascript-6">
import HPDFViewer from "@/components/HPDFViewer";
import {
  NavBar,
  Icon,
  Cell,
  CellGroup,
  Button,
  Popup,
  Field,
  Calendar,
  Notify,
  List,
  Tag,
  Picker,
  Dialog,
  DropdownMenu,
  DropdownItem,
  Checkbox,
  Cascader,
  Col,
  Row,
} from "vant";
import $ from "jquery";
import {
  SaveRecordApprove, //
  PreviewElectronicRecordReport, //
  GetRecordApproveAttributes, //
  GetRecordApproveTree,
} from "@/api/check";
import {GetServerDate} from '@/api/base';
import {GetMicroRecordApproveTree} from '@/api/microBial';
import {GetRecordCorrelationFiles,PreviewRecordCorrelationFile} from '@/api/recordQuery';
import { to } from "@/utils";
import dayjs from "dayjs";
export default {
  name: "checkApprove",
  components: {
    [NavBar.name]: NavBar,
    [Icon.name]: Icon,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Field.name]: Field,
    [Calendar.name]: Calendar,
    [Notify.name]: Notify,
    [List.name]: List,
    [Tag.name]: Tag,
    [Picker.name]: Picker,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Checkbox.name]: Checkbox,
    [Cascader.name]: Cascader,
    [Col.name]: Col,
    [Row.name]: Row,
    HPDFViewer
  },
  data() {
    return {
			showPdf: true,
      navValue: "all",
      option1: [
        {
          text: "记录复核（电子记录树）",
          value: "all",
        },
        {
          text: "记录复核（公用系统树）",
          value: "micro",
        },
      ],
      token: "",
      sampleName: "", //合并后检验样品
      showSamplePicker: false,
      sampleArr: [],
      sampleValue: "",
      showTypePicker: false,
      showPdfTypePicker: false,
      sampleNames: {
        text: "name",
        // value: "code",
      },
      logType: '',
      columns: [
        '电子记录报告单',
        '附件查看' ,
      ],
      materialCode: "",
      loading: false,
      finished: false,
      hFinished: false,
      list: [],
      showPicker: false,
      standardCode: "",
      option3: [],
      value3: "",
      batchID: "",
      testID: "",
      reportID: "",
      showItem: false,
      pdfh5: null,
      domain: "",
      isPwd: "",
      userId: "",
      saveApproveP: "",
      recordCode: "",
      treeCode: "",
      testStandard: "",
      showTextarea: false,
      message: "",
      pdfUrl: '',
      defaultUrl : '',
      pdfColumns: [],
      pdfSelectValue: '',
			selectedOptions: [],
    };
  },
  watch: {},
  computed:{
    showPdfSelect(){
      return this.logType == '附件查看'
    }
  },
  mounted() {
    this.token = localStorage.getItem("tokenKey");
    this.domain = localStorage.getItem("domain");
    this.getSampleData();
  },
  methods: {
    changeNav(val){
      this.reset();
      if(val == 'all'){
        this.getSampleData()
      }else if(val == 'micro'){
        this.getMicroSampleData()
      }
    },
    reset(){
      this.sampleName = '';
      this.logType = '';
      this.pdfSelectValue = '';
      this.sampleArr = [];
      this.pdfColumns = [];
      this.pdfUrl = '';
    },
    clickLeft() {
      this.$router.replace({ name: "home" });
    },
    handleLogTypeClick(){
      if(!this.treeCode) {
        this.$toast('请选择检验样品');
        return false;
      }
      this.showTypePicker = true;
    },
    onConfirm(value, index) {
      // console.log(`当前值: ${value}`);
      if (index == 0) {
        this.logType = '电子记录报告单'
				this.showPdf = true;
        this.pdfSelectValue = '',
        this.pdfUrl = this.defaultUrl;
      } else {
        this.logType = '附件查看'
        this.GetRecordCorrelationFilesFun()
      }
      this.showTypePicker = false;
    },
    onPdfConfirm(value, index) {
      console.log(value);
      this.pdfSelectValue = value;
      this.PreviewRecordCorrelationFileFun(value.value)
      this.showPdfTypePicker = false;
    },
    async GetRecordCorrelationFilesFun(){
      const data = await GetRecordCorrelationFiles({
        Token: this.token,
        batchID: this.batchID,
        materialCode: this.materialCode,
        testId: this.testID,
				recordCode: this.recordCode
      })
      console.log('data',data)
      if(data.ErrorCode == 0) {
        if(data.Result&&data.Result.length){
          this.pdfColumns = data.Result.map(e=>({text:e.FileName,value:e.iautoid}));
          this.pdfSelectValue = this.pdfColumns[0];
          console.log('this.pdfSelectValue',this.pdfSelectValue)
          this.PreviewRecordCorrelationFileFun(data.Result[0].iautoid)
        }
      }
    },
    async PreviewRecordCorrelationFileFun(iautoid){
      const data  = await PreviewRecordCorrelationFile({Token: this.token,iautoid})
      if(data.ErrorCode == 0) {
        var path = data.Result.targetPath;
        if(path){
          // this.pdfUrl = path;
					let type = path.substring(path.lastIndexOf('.')+1) ;
					console.log('type',this.pdfUrl)
					if(type=='pdf'){
						this.pdfUrl = path;
						this.showPdf = true;
					}else{
						let domain = localStorage.getItem('domain');
						this.pdfUrl = domain + path;
						this.showPdf = false;
					}
        }else{
          this.$toast('无附件');
          this.pdfUrl = '';
        }
        // window.open(path);
      }
    },
    async getSampleData(type) {
      var that = this;
      var queryParams = {
        Token: this.token,
      };
      const [err, res] = await to(GetRecordApproveTree(queryParams));
      if (err) return;
      var result = res.Result;
      this.dowhile(result);
			console.log(result)
      this.sampleArr = result;
			// 是否要设置默认值
			if(type) this.autoLastSelect()
            // debugger
      console.log('this.sampleArr',this.sampleArr)
    },
    async getMicroSampleData() {
      var that = this;
      var queryParams = {
        Token: this.token,
      };
      const [err, res] = await to(GetMicroRecordApproveTree(queryParams));
      if (err) return;
      var result = res.Result;
      this.dowhile(result);
      this.sampleArr = result;
			if(type) this.autoLastSelect()
    },
    dowhile(b) {
      for (var i = 0; i < b.length; i++) {
        b[i].value =b[i].batchID+'/'+b[i].code+'-'+i;
        if (b[i].children && b[i].children.length > 0) {
          this.dowhile(b[i].children);
        } else {
          delete b[i].children;
        }
      }
    },
    onSampleFinish({value, selectedOptions }) {	
			this.selectedOptions = selectedOptions;
			console.log(this.selectedOptions)	
      this.showSamplePicker = false;
      var len = selectedOptions.length;
      var toDetail = selectedOptions[len - 1];
      this.sampleName = toDetail.name;
      this.materialCode = toDetail.materialCode;
      this.testID = toDetail.testID;
      this.treeCode = toDetail.code;
      this.batchID = toDetail.batchID;
      this.reportID = toDetail.reportID;
      this.testStandard = toDetail.testStandard;
      this.recordCode = toDetail.recordCode;
      this.logType = '电子记录报告单';
      this.pdfColumns = [];
      this.pdfSelectValue = '';
				this.showPdf = true;
      this.getPreviewTestReport();
    },
		// 自动选择最后一级
		autoLastSelect() {
			console.log(this.selectedOptions)
			
			// 一共四级树
			if(this.selectedOptions.length){

				let len = this.selectedOptions.length;
				// 选中最后一级
				let last = this.selectedOptions[len - 1];
				// 选中倒数第二级
				let subLast = this.selectedOptions[len - 2];
				// 选中倒数第三级
				let nextSubLast = this.selectedOptions[len - 3];
				// 倒数第二级有子级
				if(subLast.children.length){
					// 选中倒数第二级的子级
					// 过滤掉最后选中的最后一级
					let arr = subLast.children.filter(e=>e.value!=last.value);
					nextSubLast.children.forEach(e=>{
						if(e.value == subLast.value){
							e.children = arr;
						}
					})
					let toDetail;
					if(arr.length){
						toDetail = arr[0];
								this.selectedOptions[3] = toDetail

					}else{
						for(let i=0;i<nextSubLast.children.length;i++){
							if(nextSubLast.children&&nextSubLast.children.length){
							if(nextSubLast.children[i].children.length){
								this.selectedOptions[len - 2] = nextSubLast.children[i];
								toDetail = nextSubLast.children[i].children[0];
								this.selectedOptions[3] = toDetail
								}
							}
							//终止循环
							if(toDetail) break;
						}
					}
					if(!toDetail) return;
					this.sampleValue = toDetail.value
					this.sampleName = toDetail.name;
					this.materialCode = toDetail.materialCode;
					this.testID = toDetail.testID;
					this.treeCode = toDetail.code;
					this.batchID = toDetail.batchID;
					this.reportID = toDetail.reportID;
					this.testStandard = toDetail.testStandard;
					this.recordCode = toDetail.recordCode;
					this.logType = '电子记录报告单';
					this.pdfColumns = [];
					this.pdfSelectValue = '';
					this.getPreviewTestReport();
				}
				// console.log('level3.children',level3.children)
			}
		},
    getPreviewTestReport() {
      if (this.testID == "") {
        Notify({ type: "danger", message: "请选择检验样品" });
        return false;
      }
      var that = this;
      var param = {
        Token: this.token,
        recordCode: this.treeCode,
        testId: this.testID,
      };
      PreviewElectronicRecordReport(param)
        .then((response) => {
          if (response.ErrorCode == 0) {

            var path = response.Result.path;
            that.pdfh5 = true;
            // var pdfUrl = that.domain + path;
            this.defaultUrl = path;
            this.pdfUrl = path;
            this.clickRight();
            // that.renderPdf(pdfUrl);
          }
        })
        .catch(() => {});
    },
    renderPdf(pdfurl) {
      this.pdfh5 = true;
      this.$nextTick(() => {
        this.pdfh5 = new Pdfh5("#reportPdf", {
          pdfurl,
          lazy: true,
        });
      });
      this.clickRight();
    },
    clickRight() {
      var param = {
        Token: this.token,
        recordCode: this.recordCode,
        testID: this.testID,
        testStandard: this.testStandard,
      };
      GetRecordApproveAttributes(param)
        .then((response) => {
          if (response.ErrorCode == 0) {
            this.list = response.Result;
						console.log('this.list',this.list)
          }
        })
        .catch((data) => {});
    },
		 transformDate(dataFormat) {
						if (dataFormat == "yyyy.MM.dd") {
								return "YYYY.MM.DD";
						} else if (dataFormat == "yyyy-MM-dd") {
								return "YYYY-MM-DD";
						} else if (dataFormat == "yyyy/MM/dd") {
								return "YYYY/MM/DD";
						} else if (dataFormat == "yyyy.MM.dd HH:mm") {
								return "YYYY.MM.DD HH:mm";
						} else if (dataFormat == "yyyy-MM-dd HH:mm") {
								return "YYYY-MM-DD HH:mm";
						} else if (dataFormat == "yyyy/MM/dd HH:mm") {
								return "YYYY/MM/DD HH:mm";
						} else if (dataFormat == "HH:mm") {
								return "HH:mm";
						}
				},
    pass() {
      var that = this;
      var attributeCode = "";
      if (this.list && this.list.length > 0) {
        attributeCode = this.list[0].code;
      }
			if(!attributeCode) return Notify({ type: "danger", message: "该记录未配置复核日期！" });
			Dialog.confirm({
        message: "确定通过吗？",
        confirmButtonColor: "#1e9fff",
      })
        .then(() => {
					GetServerDate().then((res)=>{
				if(res.ErrorCode == 0){
					let ServerTime = res.Result.ServerTime;
					this.list.forEach(e=>{
						if(e.type=='Date'){
							e.attributeValue = dayjs(ServerTime).format(this.transformDate(e.data[0])||'YYYY-MM-DD');
						}
					})
          var param = {
            Token: this.token,
            recordCode: this.recordCode,
            testID: this.testID,
            pass: 1,
            recordReportData: this.list.map(e=>({
							attributeCode: e.code,
							attributeName: e.name,
							attributeValue: e.attributeValue,
						})),
          };
          SaveRecordApprove(param)
            .then((response) => {
              if (response.ErrorCode == 0) {
                $("#reportPdf").html("");
                that.getSampleData(true);
                that.list = [];
                this.reset();
              }
            })
            .catch(() => {});
				}else{
					Notify({ type: "danger", message: "获取服务器时间失败！" });
				}
			}).catch(()=>{
				Notify({ type: "danger", message: "获取服务器时间失败！" });
			})

        })
        .catch(() => {});

      


    },
    reject() {
      var that = this;
      this.showTextarea = true;
    },
    recallInfo() {
      var that = this;
      var param = {
        Token: this.token,
        recordCode: this.recordCode,
        message: this.message,
        testID: this.testID,
        pass: 0,
        recordReportData: [],
      };
      SaveRecordApprove(param)
        .then((response) => {
          if (response.ErrorCode == 0) {
            $("#reportPdf").html("");
            that.showTextarea = false;
            that.getSampleData(true);
            that.list = [];
            that.sampleName = "";
            this.pdfUrl = '';
          }
        })
        .catch(() => {});
    },
    getTimeFormat(dataFormat) {
      var newTime = "";
      var nowTime = new Date();
      nowTime.setTime(nowTime.getTime());
      var year = nowTime.getFullYear();
      var month =
        nowTime.getMonth() + 1 < 10
          ? "0" + (nowTime.getMonth() + 1)
          : nowTime.getMonth() + 1;
      var date =
        nowTime.getDate() < 10 ? "0" + nowTime.getDate() : nowTime.getDate();
      var hours =
        nowTime.getHours() < 10 ? "0" + nowTime.getHours() : nowTime.getHours();
      var minutes =
        nowTime.getMinutes() < 10
          ? "0" + nowTime.getMinutes()
          : nowTime.getMinutes();
      if (dataFormat == "yyyy.MM.dd") {
        newTime = year + "." + month + "." + date;
      } else if (dataFormat == "yyyy-MM-dd") {
        newTime = year + "-" + month + "-" + date;
      } else if (dataFormat == "yyyy/MM/dd") {
        newTime = year + "/" + month + "/" + date;
      } else if (dataFormat == "yyyy.MM.dd HH:mm") {
        newTime = year + "." + month + "." + date + " " + hours + ":" + minutes;
      } else if (dataFormat == "yyyy-MM-dd HH:mm") {
        newTime = year + "-" + month + "-" + date + " " + hours + ":" + minutes;
      } else if (dataFormat == "yyyy/MM/dd HH:mm") {
        newTime = year + "/" + month + "/" + date + " " + hours + ":" + minutes;
      } else if (dataFormat == "HH:mm") {
        newTime = hours + ":" + minutes;
      }
      return newTime;
    },
  },
};
</script>

<style>
.van-dropdown-menu__bar {
  box-shadow: none;
  align-items: center;
}

.van-checkbox__icon .van-icon {
  width: 1em;
  height: 1em;
  line-height: 1em;
}
</style>
<style scoped lang="less">
	.pdf-img{
		max-width: 100vw;
	}
/deep/.van-dropdown-menu__item {
  margin-right: 10px;
  border: 1px solid #ebedf0;
  padding: 0.1rem 0 !important;
  height: 0.8rem;
  box-sizing: border-box;
}
.InspectionReview {
  margin: 0;
  padding: 0;
  height: 100%;
  // color: #fff;
}
.content {
  height: calc(100% - 1rem);
  overflow: hidden;
  /deep/.van-row {
    height: 1.2rem;
  }
}

.handleContent {
  width: 100%;
}
.van-cell {
  overflow: inherit;
}
/deep/.van-button--small {
  height: 0.7rem;
}
#reportPdf {
  height: calc(100% - 1.2rem);
  overflow: auto;
}
.rejectPopup /deep/.van-icon {
  top: 8px !important;
  right: 10px !important;
  font-size: 20px;
}
/deep/.van-dropdown-menu__bar {
  height: auto;
  background-color: transparent;
  .van-dropdown-menu__item {
    border: none;
  }
  .van-dropdown-menu__title {
    color: #fff;
  }
}
/deep/.van-dropdown-item__option--active {
  color: #1989fa;
}
.popup-content {
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .popup-content__content textarea {
    width: 100%;
    border: 1px solid #ccc;
  }
  .popup-content__footer {
    padding: 5px;
    box-sizing: border-box;
    display: flex;
    button {
      height: 30px;
    }
  }
}
</style>
